<!--新建活动-->
<template>
  <div class="app-container edit-seckill" v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" style="width:1200px">
      <el-divider content-position="center">基本信息</el-divider>
      <el-form-item label="活动名称" prop="activityName">
        <el-input style="width:452px" v-model="form.activityName" placeholder="请输入名称"/>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker placeholder="选择时间" type="datetime" value-format="timestamp" :picker-options="pickerOptions" v-model="form.startTime"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker placeholder="选择时间" type="datetime" value-format="timestamp" :picker-options="pickerOptions" v-model="form.endTime"
        ></el-date-picker>
        <!--        <div style="width: 450px;">
                  <el-col :span="11">
                    <el-form-item prop="endDate">
                      <el-date-picker type="date" value-format="timestamp" placeholder="选择日期" v-model="form.endDate" style="width: 100%;"
                      ></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col style="text-align: center" :span="2">—</el-col>
                  <el-col :span="11">
                    <el-form-item prop="endTime">
                      <el-time-picker placeholder="选择时间" value-format="timestamp" v-model="form.endTime" style="width: 100%;"></el-time-picker>
                    </el-form-item>
                  </el-col>
                </div>-->
      </el-form-item>
      <!--      <el-form-item label="标签" prop="label">
              <el-row>
                <el-col :span="4">
                  <dict-select :options="1" :value="1"></dict-select>
                </el-col>
                <el-col :span="8" :offset="1">
                  <el-row>
                    <el-col :span="3">
                      <span>自定义</span>
                    </el-col>
                    <el-col style="width: 170px">
                      <el-input type="text" v-model="form.label" placeholder="请输入自定义标签"/>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </el-form-item>-->
      <el-form-item label="是否限购" prop="num">
        <el-row>
          <el-col :span="2">
            <!--            <el-radio v-model="form.stopBy" label="1">不限购</el-radio>-->
            <span>不限购</span>
          </el-col>
          <el-col :span="6">
            <span>每人每种商品限购</span>
            <div class="audit-group">
              <el-input class="mini-number-input" v-model="form.num" type="number" :min="0"/>
            </div>
            <!--            <el-radio v-model="form.stopBy" label="2">每人每种商品限购
                          <div class="audit-group">
                            <el-form-item prop="stopByNum">
                              <el-input class="mini-number-input" v-model="form.stopByNum" type="number" :min="0"/>
                            </el-form-item>
                          </div>
                        </el-radio>-->
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="展示位置" prop="activityLocaltion">
        <el-col :span="2">
          <el-radio v-model="form.activityLocaltion" label="1">首页</el-radio>
        </el-col>
        <el-col :span="20">
          <el-radio v-model="form.activityLocaltion" label="2">内页</el-radio>
        </el-col>
      </el-form-item>
      <el-form-item label="秒杀预约" prop="appointment">
        <el-row>
          <el-col :span="2">
            <!--            <el-radio v-model="form.open" label="1">不开启</el-radio>-->
            <span>不开启</span>
          </el-col>
          <el-col :span="20">
            <span>活动开始前</span>
            <div class="audit-group">
              <el-input type="number" v-model="form.appointment" :min="0" class="mini-number-input"/>
            </div>
            <span>分钟，通知用户参加活动</span>
            <!--            <el-radio v-model="form.open" label="2">
                          活动开始前
                          <div class="audit-group">
                            <el-form-item prop="openTime">
                              <el-input type="number" v-model="form.openTime" :min="0"  class="mini-number-input"/>
                            </el-form-item>
                          </div>
                          分钟，通知用户参加活动
                        </el-radio>-->
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="适用店铺" prop="shopType">
        <template slot-scope="">
          <!--         <dict-select :options="dict.type.activity_store_type" v-model="form.type" placeholder="请选择" />-->
          <el-select v-model="form.shopType" placeholder="请选择" @change="getGoodList">
            <el-option
              v-for="item in storeType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </template>
      </el-form-item>
      <el-form-item label="添加商品" prop="skuIds">
        <!--        <el-select v-model="form.goods" multiple placeholder="请选择">
                  <el-option
                    v-for="item in goodsList"
                    :key="item.id"
                    :label="item.goodsName"
                    :value="item.goodsId"
                  @change="checkGoods">
                  </el-option>
                </el-select>-->
        <el-select
          v-model="form.goodsId"
          filterable
          remote
          placeholder="请输入关键词"
          :remote-method="getGoodList"
          v-loadmore="loadmore"
          @change="setGoodsSkus"
        >
          <el-option
            v-for="(item,index) in goodsList"
            :key="index"
            :label="item.goodsName"
            :value="item.goodsId"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="form.skuIds"
          multiple
          placeholder="请选择"
          @change="checkGoods"
          @remove-tag="removeSku"
        >
          <el-option
            v-for="item in goodsSkus"
            :key="item.skuId"
            :label="item.skuName"
            :value="item.skuId"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="商品描述" prop="description">
        <el-input style="width:452px" v-model="form.description" placeholder="请输入商品描述"/>
      </el-form-item>

      <el-divider content-position="center">商品列表</el-divider>
      <el-table :data="getSku" height="500px">
        <!--        <el-table-column label="商品编码" align="center" prop="goodsId" width="160" :show-overflow-tooltip="true"/>-->
        <el-table-column label="商品名称" align="center" prop="goodsName" width="160" :show-overflow-tooltip="true"/>
        <el-table-column label="规格" align="center" prop="skuName" width="120" :show-overflow-tooltip="true"/>
        <!--        <el-table-column label="单位" align="center" prop="returnUserName" width="100" :show-overflow-tooltip="true"/>-->
        <el-table-column label="售价" align="center" prop="price" width="120" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ $yun.priceFormatter(scope.row.price) }}
          </template>
        </el-table-column>
        <el-table-column label="指定店铺" align="center" prop="shopId" width="180"
                         :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <el-select v-model="scope.row.shopId" multiple placeholder="请选择">
              <el-option
                v-for="item in scope.row.shopList"
                :key="item.id"
                :label="item.shopName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="秒杀价格" align="center" prop="seckillPrice" width="120"
                         :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <el-input type="number" v-model="scope.row.seckillPrice" :min="0"/>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sort" width="100" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-input type="number" v-model="scope.row.sort" :min="0"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
          <template slot-scope="scope">
            <div>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="removeTableSku(scope.row.skuId)"
              >移除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table >
      <!--      <el-form-item label="指定店铺" prop="price">
              <dict-select :options="1" :value="1"></dict-select>
            </el-form-item>-->
      <el-form-item style="margin-top: 10px">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">返 回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import DateRangePicker from '@/components/DateRangePicker/index.vue'
import SelecTtimeZone from '@/components/SelecTtimeZone'
import Template from '@/views/setting/template/index.vue'
import { addList, details, getShopList, goodsList, skuList } from '@/api/activity/seckill'
import RemoteSelect from '@/components/RemoteSelect/index.vue'
import { deepClone, isNumberStr } from '@/utils'
import moment from 'moment';
export default {
  components: { RemoteSelect, Template, DateRangePicker, SelecTtimeZone },
  dicts: ['activity_store_type'],
  data() {
    const id = this.$yun.v(this.$route.query, 'id')
    const disabledDateFn = (time) => {
      return time.getTime() < Date.now();
    }
    const startTime = '';
    const disabledDateFn2 = (time) => {
      return time.getTime() > startTime.getTime();
    }
    return {
      id,
      isEdit: id != null && isNumberStr(id),
      pickerOptions:{disabledDate:disabledDateFn},
      form: {
        activityName: null,
        startDate: '',
        startTime: startTime,
        endDate: '',
        endTime: '',
        type: 0,
        num: 0,
        activityLocaltion: '1',
        appointment: 0,
        goodsId: [],
        skuIds: []
      },
      rules: {
        activityName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        startDate: [
          { required: true, message: '请选择开始日期', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '请选择结束日期', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ],
        num: [
          { required: true, message: '请输入限购数量', trigger: 'blur' }
        ],
        activityLocaltion: [
          {
            required: true, message: '请选择展示位置', trigger: 'blur'
          }
        ],
        shopType: [
          {
            required: true, message: '请选择适用店铺', trigger: 'blur'
          }
        ],
        skuIds: [
          {
            required: true, message: '请选择商品', trigger: 'blur'
          }
        ],
        description:{
          required: true, message: '请选择商品描述', trigger: 'blur'
        }
      },
      //适用店铺可选数据
      storeType: [{ label: '全部', value: '0' }, { label: '正常店铺', value: '1' }, { label: '水军店铺', value: '2' }],
      goodsForm: { current: 1, size: 20 },
      remoteSelectForm: { current: 1, size: 20 },
      //已选商品
      getGoods: [],
      //可选商品列表
      goodsList: [],
      //可选sku列表
      goodsSkus: [],
      //已选的sku
      getSku: [],
      //保存查询到的所有商品
      selfGoods: [],
      //保存查询到的所有sku
      selfSkus: [],
      activityId: this.$yun.v(this.$route.query, 'id'),
      editType: this.$yun.v(this.$route.query, 'type'),
      total:0,
      loading:false,
    }
  },
  created() {
    this.getGoodList()
    if (this.activityId) {
      this.getDetails()
    }
  },
  methods: {
    disabledDateFn (time) {
      return time.getTime() < Date.now();
    },
    loadmore(){
      if(this.total != this.goodsList.length){
        this.goodsForm.current++;
        this.getGoodList()
      }
    },
    //获取商品数据
    async getGoodList(key) {
      this.loading = true
      let setData = { ...this.goodsForm, type: this.form.type } // goodsName: key 暂时不要不知道做什么的
      await goodsList(setData).then(res => {
        if (res.success) {
          this.goodsList.push(...res.data.records)
          console.log('this.goodsList',this.goodsList)
          this.total = res.data.total
          this.loading = false
        }
      })
    },
    //选择商品变化更改可选sku
    setGoodsSkus(id) {
      this.goodsSkus = null
      this.form.skuIds = []
      let goodsId = this.form.goodsId
      skuList(goodsId).then(res => {
        this.goodsSkus = res.data
      })
    },
    //选择商品变化时 检查商品列表数据
    checkGoods() {
      let str = this.form.skuIds[this.form.skuIds.length-1]
      let obj1 = this.goodsSkus.find(obj => {
        return obj.skuId == str
      })
      if(obj1){
        this.getSku.push(obj1)
      }
      this.getSku = [...new Set(this.getSku)];
      this.getSku.forEach(item => {
        getShopList(item.skuId).then(res => {
          this.$set(item,'shopList',res.data)
        })
      })
    },
    //提交表单
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.skuIds == []) {
            this.$message.error('未指定活动商品sku')
            return
          }
          if(!this.checkArrayObjects(this.getSku)) {
            return this.$modal.msgError('商品列表中：指定店铺/秒杀价格/排序不能为空！')
          }
          let seckillGoods = [], setData = {}
          for (let i = 0; i < this.getSku.length; i++) {
            let item = this.getSku[i]
            seckillGoods.push({
              skuId: item.skuId,
              name: item.goodsname,
              skuName: item.skuName,
              images: item.images,
              price: item.price,
              seckillPrice: item.seckillPrice,
              sort: item.sort,
              shopId: item.shopId,
              infoId: item.infoId
            })
          }
          if (this.activityId) {
            this.form.startTime = parseFloat(this.form.startTime) // 格式化为年月日时分秒
            this.form.endTime = parseFloat(this.form.endTime);// 格式化为年月日时分秒
          }
          addList({ ...this.form, seckillGoods, shopType: this.form.shopType, id: this.id }).then(response => {
            this.$modal.msgSuccess(this.id ? '修改成功' : '新增成功')
            // 关闭当前tabs
            this.$store.dispatch('tagsView/delView', this.$route)
            // 跳转路由
            this.$router.replace({ path: '/activity/seckill' })
          })
        }
      })
    },
    //点击tag移除已选
    removeSku: function(id) {
      // 使用findIndex方法查找满足条件的对象的索引
      let index = this.getSku.findIndex(item => item.skuId == id);
      // 如果找到了满足条件的对象，则删除该对象
      if (index !== -1) this.getSku.splice(index, 1);
    },
    //点击table移除
    removeTableSku: function(value) {
      this.removeSku(value)
      let form =deepClone(this.form) ;
      let index = form.skuIds.indexOf(value)
      if (index != -1) {
        form.skuIds.splice(index, 1)
      }
      this.form = form;
    },
    cancel() {
      // 关闭当前tabs
      this.$store.dispatch('tagsView/delView', this.$route)
      // 跳转路由
      this.$router.replace({ path: '/activity/seckill' })

    },
    //获取详情数据
    getDetails: function() {
      details(this.activityId).then(res => {
        if (res.success) {
          this.form = res.data
          this.form.activityLocaltion = res.data.activityLocaltion.toString()
          let skuIds = [], detailsGetSku = [],goodsSkus=[];
          for (let i = 0; i < res.data.seckillGoods.length; i++) {
            let item = res.data.seckillGoods[i]
            let shopId = [], getSkuItem = {}
            for (let j = 0; j < item.shop.length; j++) {
              let good = item.shop[j]
              shopId.push(good.id)
            }
            skuIds.push(item.skuId)
            getSkuItem = {
              goodsName: item.name,
              skuName: item.skuName,
              price: item.price,
              seckillPrice: item.seckillPrice,
              sort: item.sort,
              skuId: item.skuId,
              infoId: item.infoId,
              images: item.images
            }
            detailsGetSku.push({ ...getSkuItem, shopList: item.shop, shopId: shopId })
          }
          this.form.skuIds = skuIds
          this.goodsSkus = res.data.seckillGoods;
          this.form.shopType = this.form.shopType + ''
          this.form.type = this.form.shopType
          this.getSku = detailsGetSku
        }
      })
    },
    // 判断数组中的某个值是否为空
    checkArrayObjects(array) {
      for (let i = 0; i < array.length; i++) {
        const obj = array[i];
        if (!obj.shopId || !obj.seckillPrice || !obj.sort) {
          return false;
        }
      }
      return true;
    }
  }

}

</script>

<style lang="scss" scoped>
.el-table__body-wrapper .el-table__empty-block {
  height: 100px !important
}

.mini-number-input {
  width: 100px;
}
</style>
